import re
from fastapi import Request

from models.blog import BlogVisit
from service import blog_service
from utils.blog_utils import get_user_agent_info, get_client_ip
from config.database import SessionLocal
from middleware.exceptions import AppException


async def blog_visit_middleware(request: Request, call_next):
    # 检查路径是否匹配
    if match := re.match(r"^/blog/(\d+)/content$", request.url.path):

        # 获取客户端信息
        ip = get_client_ip(request)
        user_agent = request.headers.get("User-Agent", "")
        os, browser = get_user_agent_info(user_agent)
        blog_id = int(match.group(1))

        # 创建访问记录
        blog_visit = BlogVisit(
            ip=ip,
            os=os,
            browser=browser,
            uri=request.url.path,
            blog_id=blog_id
        )

        db = SessionLocal()
        try:
            blog_service.add_blog_visit(db, blog_visit)
            db.commit()
        except Exception as e:
            db.rollback()
            raise AppException(f"新增博客{blog_id}访问记录失败: {e}")
        finally:
            db.close()

    # 继续处理请求
    response = await call_next(request)
    return response
